//
//  ViewController.m
//  CC_Weather
//
//  Created by rimi on 16/9/21.
//  Copyright © 2016年 cc. All rights reserved.
//

#import "ViewController.h"
@import CoreLocation;
@import MapKit;

@interface ViewController ()<CLLocationManagerDelegate, MKMapViewDelegate>

@property(nonatomic, strong)CAShapeLayer *shapeLayer;
@property(nonatomic,copy) NSString *key;
- (void)initUserInterface;/**<初始化界面 */
- (void)initDataSource;/**<获得数据 */
- (void)loadData;/**<赋值 */

@end



@implementation ViewController


#pragma mark - life circle
- (void)viewDidLoad {
    [super viewDidLoad];
    self.key = @"8d525c1b283b62f33876dc84c877d5e9";
    //解档
    NSString *plistPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
    plistPath = [plistPath stringByAppendingString:@"/data.plist"];
    NSData *data = [NSData dataWithContentsOfFile:plistPath];
    _dataSource= [NSKeyedUnarchiver unarchiveObjectWithData:data];
    
    //赋初始值
    _city = _dataSource[@"realtime"][@"city_name"] ? _dataSource[@"realtime"][@"city_name"] : @"成都";
    self.title = _dataSource[@"realtime"][@"city_name"] ? _dataSource[@"realtime"][@"city_name"] : @"成都";
    
    //初始化界面
    [self initDataSource];
    [self initUserInterface];
    
}

//移动到动画位置
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    //偏移布局，方便实现进入动画
    _temperatureLabel.frame = CGRectMake(-300, SCREEN_HEIGHT * 0.36, SCREEN_WIDTH * 0.6, SCREEN_HEIGHT * 0.13);
    _dateLabel.frame = CGRectMake(-300, SCREEN_HEIGHT * 0.48, SCREEN_WIDTH * 0.7, SCREEN_HEIGHT * 0.06);
    _weatherInformationLabel.frame = CGRectMake(-300, SCREEN_HEIGHT * 0.52, SCREEN_WIDTH * 0.5, SCREEN_HEIGHT * 0.06);
    _upImageView.frame = CGRectMake(-300, SCREEN_HEIGHT *0.58, SCREEN_WIDTH * 0.06, SCREEN_HEIGHT * 0.03);
    _maxTemperatureLabel.frame = CGRectMake(-300, SCREEN_HEIGHT * 0.57, SCREEN_WIDTH * 0.1, SCREEN_HEIGHT * 0.05);
    _downImageView.frame = CGRectMake(-300, SCREEN_HEIGHT *0.58, SCREEN_WIDTH * 0.06, SCREEN_HEIGHT * 0.03);
    _minTemperatureLabel.frame = CGRectMake(-300, SCREEN_HEIGHT * 0.57, SCREEN_WIDTH * 0.1, SCREEN_HEIGHT * 0.05);
    _siteImageView.frame = CGRectMake(-300, SCREEN_HEIGHT * 0.625, SCREEN_WIDTH * 0.080, SCREEN_HEIGHT * 0.04);
    _siteLabel.frame = CGRectMake(-300, SCREEN_HEIGHT *0.623, SCREEN_WIDTH * 0.2, SCREEN_HEIGHT * 0.05);
    _predictedView.frame = CGRectMake(0, SCREEN_HEIGHT * 1.3, SCREEN_WIDTH, SCREEN_HEIGHT * 0.3);
    //透明度
    _temperatureLabel.alpha = 0;
    _dateLabel.alpha = 0;
    _weatherInformationLabel.alpha = 0;
    _upImageView.alpha = 0;
    _maxTemperatureLabel.alpha = 0;
    _downImageView.alpha = 0;
    _minTemperatureLabel.alpha = 0;
    _siteLabel.alpha = 0;
    _siteImageView.alpha = 0;
    _predictedView.alpha = 0;
}

//开始动画
-(void)viewDidAppear:(BOOL)animated{
    
    [super viewDidAppear:animated];
    //temperatureLabel
    [UIView animateWithDuration:0.7 delay:0.2 usingSpringWithDamping:0.6 initialSpringVelocity:0 options:0 animations:^{
        _temperatureLabel.frame = CGRectMake(SCREEN_WIDTH * 0.13, SCREEN_HEIGHT * 0.36, SCREEN_WIDTH * 0.6, SCREEN_HEIGHT * 0.13);
        _temperatureLabel.alpha = 1;
    } completion:nil];
    
    //dateLabel
    [UIView animateWithDuration:0.7 delay:0.3 usingSpringWithDamping:0.6 initialSpringVelocity:0 options:0 animations:^{
        _dateLabel.frame = CGRectMake(SCREEN_WIDTH * 0.1, SCREEN_HEIGHT * 0.48, SCREEN_WIDTH * 0.7, SCREEN_HEIGHT * 0.06);
        _dateLabel.alpha = 1;
    } completion:nil];
    
    //weatherInformationLabel
    [UIView animateWithDuration:0.7 delay:0.4 usingSpringWithDamping:0.6 initialSpringVelocity:0 options:0 animations:^{
        _weatherInformationLabel.frame = CGRectMake(SCREEN_WIDTH * 0.1, SCREEN_HEIGHT * 0.52, SCREEN_WIDTH * 0.5, SCREEN_HEIGHT * 0.06);
        _weatherInformationLabel.alpha = 1;
    } completion:nil];
    
    //upImageView & downImageView
    [UIView animateWithDuration:0.7 delay:0.5 usingSpringWithDamping:0.6 initialSpringVelocity:0 options:0 animations:^{
        _upImageView.frame = CGRectMake(SCREEN_WIDTH * 0.1, SCREEN_HEIGHT *0.58, SCREEN_WIDTH * 0.06, SCREEN_HEIGHT * 0.03);
        _upImageView.alpha = 1;
        _maxTemperatureLabel.frame = CGRectMake(SCREEN_WIDTH * 0.17, SCREEN_HEIGHT * 0.57, SCREEN_WIDTH * 0.1, SCREEN_HEIGHT * 0.05);
        _maxTemperatureLabel.alpha = 1;
        _downImageView.frame = CGRectMake(SCREEN_WIDTH * 0.32, SCREEN_HEIGHT *0.58, SCREEN_WIDTH * 0.06, SCREEN_HEIGHT * 0.03);
        _downImageView.alpha = 1;
        _minTemperatureLabel.frame = CGRectMake(SCREEN_WIDTH * 0.39, SCREEN_HEIGHT * 0.57, SCREEN_WIDTH * 0.1, SCREEN_HEIGHT * 0.05);
        _minTemperatureLabel.alpha = 1;
    } completion:nil];
    
    //siteImageView
    [UIView animateWithDuration:0.7 delay:0.6 usingSpringWithDamping:0.6 initialSpringVelocity:0 options:0 animations:^{
        _siteImageView.frame = CGRectMake(SCREEN_WIDTH * 0.1, SCREEN_HEIGHT * 0.625, SCREEN_WIDTH * 0.080, SCREEN_HEIGHT * 0.04);
        _siteImageView.alpha = 1;
        _siteLabel.frame = CGRectMake(SCREEN_WIDTH * 0.2, SCREEN_HEIGHT *0.623, SCREEN_WIDTH * 0.2, SCREEN_HEIGHT * 0.05);
        _siteLabel.alpha = 1;
    } completion:nil];
    
    //predictedView
    [UIView animateWithDuration:0.7 delay:0.8 usingSpringWithDamping:0.6 initialSpringVelocity:0 options:0 animations:^{
        _predictedView.frame = CGRectMake(0, SCREEN_HEIGHT * 0.7, SCREEN_WIDTH, SCREEN_HEIGHT * 0.3);
        _predictedView.alpha = 1;
    } completion:nil];

}


#pragma mark - initUserInterface & initDataSource

//获得数据
- (void)initDataSource{
    
    //检查网络
    [NetRequst cheackTheNet:^(BOOL have) {
        if (have) {
            //开始请求
            NSString *utf8 = [[NSString stringWithFormat:@"http://op.juhe.cn/onebox/weather/query?cityname=%@&key=f626acad6640a9434fb4b8e6a46326cc",_city] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
            [NetRequst POST:utf8 parameters:nil success:^(id responseObject) {
                //判断查找城市成功与否
                if ([responseObject[@"reason"] isEqualToString:@"查询不到该城市的信息"]) {
                    //没有查到城市
                    self.title = _dataSource[@"realtime"][@"city_name"];
                    _city = _dataSource[@"realtime"][@"city_name"];
                    [NetRequst alert:@"没有找到该城市!"];
                    
                }else{
                    //查询到城市10012
                    if (![(NSDictionary *)responseObject[@"error_code"] isEqual:@(10012)]) {
                        _dataSource = (NSDictionary *)responseObject[@"result"][@"data"];
                    }
                    //归档
                    NSString *plistPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
                    plistPath = [plistPath stringByAppendingString:@"/data.plist"];
                    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:_dataSource];
                    BOOL success = [data writeToFile:plistPath atomically:YES];
                    NSLog(@"归档：%d",success);
                    [self loadData];
                }
                
            } fail:^(NSError *error) {
                NSLog(@"error :%@",error);
            }];
            
        }else{
            //永远有数据加载
            if (_dataSource[@"realtime"][@"city_name"]) {
                _city = _dataSource[@"realtime"][@"city_name"];
                [self loadData];
            }
            [NetRequst alert:@"没有网络"];
        }
    }];
    
    
    
}


//界面初始化
-(void)initUserInterface{
    
    self.view.backgroundColor = [UIColor colorWithRed:0.432 green:0.5245 blue:0.705 alpha:1.0];
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
    _isNight = YES;
    
    //背景图
    _backgroundImageView = [[UIImageView alloc]initWithFrame:self.view.frame];
    _backgroundImageView.image = [UIImage imageNamed:@"backgroundImage"];
    [self.view addSubview:_backgroundImageView];
    
    //WeatherAnimation天气动画
    _weatherAnimation = [[WeatherAnimation alloc]initWithFrame:self.view.frame];
    [_backgroundImageView addSubview:_weatherAnimation];
    
    //indicatorView
    _indicatorView = [[UIActivityIndicatorView alloc]init];
    _indicatorView.center = CGPointMake(SCREEN_WIDTH * 0.5, 69);
    [_indicatorView hidesWhenStopped];
    [self.view addSubview:_indicatorView];
    
    //navigationBar
    self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor whiteColor]};
    self.navigationController.navigationBar.translucent = true;
    [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.shadowImage = [UIImage new];
    
    
    //temperatureLabel
    _temperatureLabel = [[UILabel alloc]initWithFrame:CGRectMake(SCREEN_WIDTH * 0.13, SCREEN_HEIGHT * 0.36, SCREEN_WIDTH * 0.6, SCREEN_HEIGHT * 0.13)];
    _temperatureLabel.textAlignment = NSTextAlignmentLeft;
    //_temperatureLabel.backgroundColor = [UIColor redColor];
    _temperatureLabel.font = [UIFont fontWithName:@"CourierNewPSMT" size:90];
    _temperatureLabel.textColor = [UIColor colorWithRed:0.9524 green:0.9546 blue:0.9873 alpha:1.0];
    [self.view addSubview:_temperatureLabel];
    
    
    //_dateLabel
    _dateLabel = [[UILabel alloc]initWithFrame:CGRectMake(SCREEN_WIDTH * 0.1, SCREEN_HEIGHT * 0.48, SCREEN_WIDTH * 0.7, SCREEN_HEIGHT * 0.06)];
    //_dateLabel.backgroundColor = [UIColor grayColor];
    _dateLabel.font = [UIFont systemFontOfSize:17];
    _dateLabel.textColor = [UIColor colorWithRed:0.9524 green:0.9546 blue:0.9873 alpha:1.0];
    [self.view addSubview:_dateLabel];
    
    
    //_weatherInformationLabel
    _weatherInformationLabel = [[UILabel alloc]initWithFrame:CGRectMake(SCREEN_WIDTH * 0.1, SCREEN_HEIGHT * 0.52, SCREEN_WIDTH * 0.5, SCREEN_HEIGHT * 0.06)];
    //_weatherInformationLabel.backgroundColor = [UIColor yellowColor];
    _weatherInformationLabel.font = [UIFont systemFontOfSize:17];
    _weatherInformationLabel.textColor = [UIColor colorWithRed:0.9524 green:0.9546 blue:0.9873 alpha:1.0];
    [self.view addSubview:_weatherInformationLabel];
    
    
    //max temperatureImage
    _upImageView = [[UIImageView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH * 0.1, SCREEN_HEIGHT *0.58, SCREEN_WIDTH * 0.06, SCREEN_HEIGHT * 0.03)];
    _upImageView.image = [UIImage imageNamed:@"max_w"];
    [self.view addSubview:_upImageView];
    
    //max temperatureLabel
    _maxTemperatureLabel = [[UILabel alloc]initWithFrame:CGRectMake(SCREEN_WIDTH * 0.17, SCREEN_HEIGHT * 0.57, SCREEN_WIDTH * 0.1, SCREEN_HEIGHT * 0.05)];
    _maxTemperatureLabel.font = [UIFont systemFontOfSize:17];
    _maxTemperatureLabel.textColor = [UIColor colorWithRed:0.9524 green:0.9546 blue:0.9873 alpha:1.0];
    
    [self.view addSubview:_maxTemperatureLabel];
    
    
    //min temperatureImage
    _downImageView = [[UIImageView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH * 0.32, SCREEN_HEIGHT *0.58, SCREEN_WIDTH * 0.06, SCREEN_HEIGHT * 0.03)];
    _downImageView.image = [UIImage imageNamed:@"min_w"];
    [self.view addSubview:_downImageView];
    
    //min temperatureLabel
    _minTemperatureLabel = [[UILabel alloc]initWithFrame:CGRectMake(SCREEN_WIDTH * 0.39, SCREEN_HEIGHT * 0.57, SCREEN_WIDTH * 0.1, SCREEN_HEIGHT * 0.05)];
    _minTemperatureLabel.font = [UIFont systemFontOfSize:17];
    _minTemperatureLabel.textColor = [UIColor colorWithRed:0.9524 green:0.9546 blue:0.9873 alpha:1.0];
    [self.view addSubview:_minTemperatureLabel];
    
    //site image
    _siteImageView = [[UIImageView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH * 0.1, SCREEN_HEIGHT * 0.625, SCREEN_WIDTH * 0.080, SCREEN_HEIGHT * 0.04)];
    _siteImageView.image = [UIImage imageNamed:@"site_w"];
    [self.view addSubview:_siteImageView];
    
    //site Label
    _siteLabel = [[UILabel alloc]initWithFrame:CGRectMake(SCREEN_WIDTH * 0.2, SCREEN_HEIGHT *0.623, SCREEN_WIDTH * 0.2, SCREEN_HEIGHT * 0.05)];
    _siteLabel.textColor = [UIColor colorWithRed:0.9524 green:0.9546 blue:0.9873 alpha:1.0];
    _siteLabel.font = [UIFont systemFontOfSize:17];
    [self.view addSubview:_siteLabel];
    
    //预测模块
    _predictedView = [[UIView alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT * 0.7, SCREEN_WIDTH, SCREEN_HEIGHT * 0.25)];
    [self.view addSubview:_predictedView];
    //预测子项
    _predictedDay = [NSMutableArray array];
    _predictedtemperature = [NSMutableArray array];
    _predictedWeatherImage = [NSMutableArray array];
    
    for (NSInteger index = 0; index < 4; index ++) {
        //星期几
        UILabel *dayLabel = [[UILabel alloc]initWithFrame:CGRectMake(SCREEN_WIDTH * 0.25 * index, SCREEN_HEIGHT * 0.3 * 0.05, SCREEN_WIDTH * 0.25, SCREEN_HEIGHT * 0.05)];
        dayLabel.textAlignment = NSTextAlignmentCenter;
        dayLabel.font = [UIFont fontWithName:@"CourierNewPSMT" size:17];
        dayLabel.textColor = [UIColor colorWithRed:0.9524 green:0.9546 blue:0.9873 alpha:1.0];
        [_predictedView addSubview:dayLabel];
        [_predictedDay addObject:dayLabel];
        
        //天气图片
        UIImageView *weatherImageView = [[UIImageView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH * (0.25 * index + 0.05), SCREEN_HEIGHT * 0.3 * 0.3, SCREEN_WIDTH * 0.115, SCREEN_HEIGHT * 0.055)];
        //weatherImageView.backgroundColor = [UIColor yellowColor];
        [_predictedView addSubview:weatherImageView];
        [_predictedWeatherImage addObject:weatherImageView];
        
        //温度
        UILabel *temperatureLabel = [[UILabel alloc]initWithFrame:CGRectMake(SCREEN_WIDTH * 0.25 * index, SCREEN_HEIGHT * 0.3 * 0.6, SCREEN_WIDTH * 0.25, SCREEN_HEIGHT * 0.05)];
        temperatureLabel.textAlignment = NSTextAlignmentCenter;
        temperatureLabel.font = [UIFont systemFontOfSize:14];
        temperatureLabel.textColor = [UIColor colorWithRed:0.9524 green:0.9546 blue:0.9873 alpha:1.0];
        [_predictedView addSubview:temperatureLabel];
        [_predictedtemperature addObject:temperatureLabel];
    }
    
    //positionButton
    _positionButton = [[UIButton alloc]initWithFrame:CGRectMake(SCREEN_WIDTH * 0.87, SCREEN_HEIGHT * 0.94, 40, 40)];
    [_positionButton setBackgroundImage:[UIImage imageNamed:@"position"] forState:UIControlStateNormal];
    [_positionButton addTarget:self action:@selector(startPosition) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_positionButton];
    
    
    
}



#pragma mark - other method

//赋值
- (void)loadData{
    
    //backgroundImage & 动画
    if ([_dataSource[@"realtime"][@"weather"][@"info"] containsString:@"雨"]) {
        
        _backgroundImageView.image = [UIImage imageNamed:@"rain"];
         //雨的动画
        [_weatherAnimation showRain];
        
    }else if ([_dataSource[@"realtime"][@"weather"][@"info"] containsString:@"雾"]){
        
        _backgroundImageView.image = [UIImage imageNamed:@"fog"];
        //云的动画
        [_weatherAnimation showCloudy];
        
        
    }else if ([_dataSource[@"realtime"][@"weather"][@"info"] containsString:@"阴"]){
        
        _backgroundImageView.image = [UIImage imageNamed:@"fog"];
        //云的动画
        [_weatherAnimation showCloudy];
        
    }else if ([_dataSource[@"realtime"][@"weather"][@"info"] containsString:@"晴"]){
        
        _backgroundImageView.image = [UIImage imageNamed:@"sun"];
        //太阳的动画
        [_weatherAnimation showSun];
        
    }else if ([_dataSource[@"realtime"][@"weather"][@"info"] containsString:@"多云"]){
        
        _backgroundImageView.image = [UIImage imageNamed:@"backgroundImage.jpg"];
        //云的动画
        [_weatherAnimation showCloudy];
        
    }else if ([_dataSource[@"realtime"][@"weather"][@"info"] containsString:@"雪"]){
        
        _backgroundImageView.image = [UIImage imageNamed:@"fog"];
        //雪的动画
        [_weatherAnimation showSnow];

    }else {
        _backgroundImageView.image = [UIImage imageNamed:@"rain"];
    }
    
    
    //temperatureLabel
    _temperatureLabel.text = [NSString stringWithFormat:@"%@°",_dataSource[@"realtime"][@"weather"][@"temperature"]];
    
    //_dateLabel
    _dateLabel.text = [NSString stringWithFormat:@"%@  星期%@",_dataSource[@"realtime"][@"date"],_dataSource[@"weather"][0][@"week"]];
    
    //_weatherInformationLabel
    _weatherInformationLabel.text = [NSString stringWithFormat:@"%@ %@ , %@",_dataSource[@"realtime"][@"wind"][@"power"],_dataSource[@"realtime"][@"wind"][@"direct"],_dataSource[@"realtime"][@"weather"][@"info"]];
    
    //max TemperatureLabel
    NSInteger maxTemp = [_dataSource[@"realtime"][@"weather"][@"temperature"] integerValue] + 5;
    _maxTemperatureLabel.text = [NSString stringWithFormat:@"%ld°",maxTemp];
    
    //min TemperatureLabel
    NSInteger minTemp = [_dataSource[@"realtime"][@"weather"][@"temperature"] integerValue] - 5;
    _minTemperatureLabel.text = [NSString stringWithFormat:@"%ld°",minTemp];
    
    //site
    _siteLabel.text = _dataSource[@"realtime"][@"city_name"];
    
    //未来几天的天气预报
    for (NSInteger index = 0; index < 4; index ++) {
        //星期几
        _predictedDay[index].text = [NSString stringWithFormat:@"星期%@",_dataSource[@"weather"][index +1][@"week"]];
        
        //天气图片
        if ([_dataSource[@"weather"][index + 1][@"info"][@"day"][1] containsString:@"晴"]) {
            _predictedWeatherImage[index].image = [UIImage imageNamed:@"min_sun"];
        }else if ([_dataSource[@"weather"][index + 1][@"info"][@"day"][1] containsString:@"多云"]){
            _predictedWeatherImage[index].image = [UIImage imageNamed:@"min_cloudy"];
        }else if ([_dataSource[@"weather"][index + 1][@"info"][@"day"][1] containsString:@"阴"]){
             _predictedWeatherImage[index].image = [UIImage imageNamed:@"min_overcast"];
        }else if ([_dataSource[@"weather"][index + 1][@"info"][@"day"][1] containsString:@"雾"]){
            _predictedWeatherImage[index].image = [UIImage imageNamed:@"min_fog"];
        }else if ([_dataSource[@"weather"][index + 1][@"info"][@"day"][1] containsString:@"雪"]){
            _predictedWeatherImage[index].image = [UIImage imageNamed:@"min_snow"];
        }else if ([_dataSource[@"weather"][index + 1][@"info"][@"day"][1] containsString:@"小雨"]){
            _predictedWeatherImage[index].image = [UIImage imageNamed:@"littlerain"];
        }else if ([_dataSource[@"weather"][index + 1][@"info"][@"day"][1] containsString:@"中雨"]){
            _predictedWeatherImage[index].image = [UIImage imageNamed:@"middlerain"];
        }else if ([_dataSource[@"weather"][index + 1][@"info"][@"day"][1] containsString:@"大雨"]){
            _predictedWeatherImage[index].image = [UIImage imageNamed:@"bigrain"];
        }else if ([_dataSource[@"weather"][index + 1][@"info"][@"day"][1] containsString:@"阵雨"]){
            _predictedWeatherImage[index].image = [UIImage imageNamed:@"shower"];
        }
        
        
        //温度
        _predictedtemperature[index].text = [NSString stringWithFormat:@"%@ | %@°",_dataSource[@"weather"][index +1][@"info"][@"day"][1] ,_dataSource[@"weather"][index +1][@"info"][@"day"][2]];
    }
}


//设置按钮
- (IBAction)setItemPress:(UIBarButtonItem *)sender {
    
    [self.navigationController pushViewController:[[SetViewController alloc]init] animated:YES];
}


//加号切换城市
- (IBAction)showCity:(UIBarButtonItem *)sender {
    
    //选区城市
    SGPickerView *picker = [[SGPickerView alloc]init];
    picker.pickerViewType = SGPickerViewTypeCenter;
    [picker show];
    picker.locationMessage = ^(NSString *str){
        NSRange range = [str rangeOfString:@" "];
        _city = [str substringFromIndex:range.location+1];
        self.title = _city;
        [self initDataSource];
    };
}

//定位

- (void)startPosition{

    //定位
    [self loadLocation];
    [NetRequst alert:@"开始定位"];
    
}

//开始定位
- (void)loadLocation {
    //先配置info.plist 关键字 NSLocationWhenInUseUsageDescription NSLocationAlwaysUsageDescription 配置设置选项
    /**
     NSLocationAlwaysUsageDescription 后台一直开启定位服务
     NSLocationWhenInUseUsageDescription 只在程序运行时开启定位服务
     */
    //定位服务是否可用
    if (![CLLocationManager locationServicesEnabled]) {
        NSLog(@"定位服务不可用");
    }
    _locationmanager = [[CLLocationManager alloc] init];
    //弹出对话框获取用户权限
    [_locationmanager requestWhenInUseAuthorization];
    _locationmanager.delegate = self;
    //定位精度
    _locationmanager.desiredAccuracy = kCLLocationAccuracyBest;
    //位置更新的最小距离
    _locationmanager.distanceFilter = kCLDistanceFilterNone;
    //启动定位
    [_locationmanager startUpdatingLocation];
}

//获得定位信息
- (void)locationManager:(CLLocationManager *)manager
     didUpdateLocations:(NSArray<CLLocation *> *)locations {
    NSLog(@"位置信息：%@",manager.location);
    //停止定位
    [manager stopUpdatingLocation];
    
    CLLocation *currentLocation = [locations lastObject];
    CLGeocoder * geoCoder = [[CLGeocoder alloc] init];
    NSString *currentCity = [[NSString alloc]init];
    //反编码
    [geoCoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        if (placemarks.count > 0) {
            CLPlacemark *placeMark = placemarks[0];
            _city = placeMark.locality;
            self.title = _city;
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self initDataSource];
                });
            });
            
            if (!currentCity) {
                [NetRequst alert:@"无法定位当前城市"];
            }
            NSLog(@"city：%@",_city); //这就是当前的城市
        }
        else if (error == nil && placemarks.count == 0) {
            NSLog(@"No location and error return");
        }
        else if (error) {
            NSLog(@"location error: %@ ",error);
        }
        
    }];
    
    
    NSString *urlStr = [NSString stringWithFormat:@"http://api.tianditu.gov.cn/geocoder?postStr={'lon':%@,'lat':%@,'ver':1}&type=geocode&tk=%@",@(currentLocation.coordinate.longitude),@(currentLocation.coordinate.latitude),self.key];
    urlStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
//    [NetRequst GET:urlStr parameters:nil success:^(id responseObject) {
//        //判断查找城市成功与否
//        NSLog(@"%@",responseObject);
//
//    } fail:^(NSError *error) {
//        NSLog(@"error :%@",error);
//    }];
//    return;
    
    NSURL *url = [[NSURL alloc] initWithString:urlStr];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
//    request.HTTPMethod = @"GET";
//    request.allowsCellularAccess = true;
//    request.timeoutInterval = 30;
//    [request setValue:@"text/html; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
//    request.allHTTPHeaderFields = @{@"Content-Type":@"text/html"};
//    request.HTTPBody = [[NSString stringWithFormat:@"postStr={'lon':%@,'lat':%@,'ver':1}&type=geocode&tk=%@",@(currentLocation.coordinate.longitude),@(currentLocation.coordinate.latitude),self.key] dataUsingEncoding:NSUTF8StringEncoding];
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
//    config.allowsCellularAccess = true;
//    config.HTTPAdditionalHeaders = @{@"Content-Type":@"application/xml"};
    NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
    [_indicatorView startAnimating];
    [[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error) {
            NSLog(@"错误：%@",error);
        } else {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSLog(@"%@",dic);
        }
        }] resume] ;
    
    
}



#pragma mark - protocol
- (UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}

//点击刷新
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [_indicatorView startAnimating];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        [NSThread sleepForTimeInterval:2];
        //切换到主线程
        dispatch_sync(dispatch_get_main_queue(), ^{
            [_indicatorView stopAnimating];
            [self initDataSource];
        });
    });
    
}

@end
